package com.lanlian.cayman.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.lanlian.cayman.CalculationService;
import com.lanlian.cayman.HqMsg;
import com.lanlian.cayman.R;
import com.lanlian.cayman.activity.SearchTreatyActivity;
import com.lanlian.cayman.proto.ProtoManager;
import com.lanlian.cayman.socket.MySocketManager;
import com.lanlian.cayman.socket.SocketCallImpl;
import com.lanlian.cayman.utils.VolleyRequestUtils;
import com.lanlian.commonlib.base.BaseActivity;
import com.lanlian.commonlib.base.BaseFragment;
import com.lanlian.commonlib.bean.BaseResponse;
import com.lanlian.commonlib.bean.ReqGetMarket;
import com.lanlian.commonlib.common.SystemConfig;
import com.lanlian.commonlib.data.RespMarket;
import com.lanlian.commonlib.network.INetWorkCallback;
import com.lanlian.commonlib.util.LogUtils;
import com.lanlian.commonlib.util.OnEventID;
import com.lanlian.commonlib.util.OnEventUtils;
import com.lanlian.utillib.CommonUtils;
import com.lanlian.utillib.DisplayUtil;
import com.oms.rpc.protobuf.OMSTradeReq;
import com.oms.rpc.protobuf.OMSTradeRsp;
import com.oms.rpc.protobuf.TickHqResp;
import com.oms.rpc.protobuf.YsHqInfo;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ColorTransitionPagerTitleView;

import java.util.ArrayList;

/**
 * <pre>
 *     author : yuguohe
 *     e-mail : 1374405188@qq.com
 *     date   : 2018/8/9 13:40
 *     desc   : 行情TAB
 *     version: 1.0
 * </pre>
 */
public class MarketFragment extends BaseFragment implements View.OnClickListener {

    private ImageView mImgSearch;
    private SmartRefreshLayout mLayRefresh;
    private MagicIndicator mMagicIndicator;
    private ViewPager mViewPager;

    public static RespMarket mRespMarket;
    private TickHqResp mTickHqResp;
    private boolean mTickHqRespReady;
    private ArrayList<String> mTitleList = new ArrayList<>();
    private ArrayList<String> mTitleId = new ArrayList<>();
    private ArrayList<MarketInfoFragment> mFragments = new ArrayList<>();
    private boolean mIsFirst = true;

    public static RespMarket getRespMarket() {
        if (mRespMarket == null) {
            mRespMarket = new RespMarket();
        }
        return mRespMarket;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!CommonUtils.isListEmpty(mFragments)) {
            for (MarketInfoFragment mFragment : mFragments) {
                mFragment.setIsParentVisibleToUser(!hidden);
            }
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_market, null);
        initView(view);
        setListeners();
        initData();
        getTickHq();
        initPermission();
        return view;
    }

    @Override
    protected void initView(View view) {
        super.initView(view);
        mImgSearch = view.findViewById(R.id.img_search);
        mLayRefresh = view.findViewById(R.id.lay_refresh);
        mMagicIndicator = view.findViewById(R.id.magic_indicator);
        mViewPager = view.findViewById(R.id.view_pager);
    }

    @Override
    protected void setListeners() {
        super.setListeners();
        mImgSearch.setOnClickListener(this);
        mLayRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                initData();
            }
        });
    }

    private void getTickHq() {
        ProtoManager pm = new ProtoManager();
        OMSTradeReq.Builder oms = pm.getRequst(6);
        OMSTradeReq om = oms.build();
        SocketCallImpl socketCall = new SocketCallImpl((BaseActivity) getActivity()) {
            @Override
            public void error(Exception e) {
                mTickHqRespReady = true;
            }

            @Override
            public void message(byte[] data) {
                mTickHqRespReady = true;
                try {
                    OMSTradeRsp oms = OMSTradeRsp.parseFrom(data);
                    mTickHqResp = oms.getTickhqResp();
                    setData();
                } catch (Exception e) {
                    LogUtils.e("MarketFragment", e.getMessage());
                }
            }
        };
        MySocketManager ms = new MySocketManager();
        ms.setCongLian(true);
        ms.sendData(om.toByteArray(), socketCall);
    }

    @Override
    public void initData() {
        VolleyRequestUtils.getInstance().sendRequest(this.toString(), new ReqGetMarket(), new INetWorkCallback() {
            @Override
            public void onSuccess(Object response) {
                mLayRefresh.finishRefresh();
                mRespMarket = (RespMarket) response;
                if (mIsFirst) {
                    mIsFirst = false;
                    startCalculationService();
                    initFragments();
                    initNavigator();
                    setData();
                }
            }

            @Override
            public void onFail(BaseResponse baseResponse) {
                mLayRefresh.finishRefresh();
            }
        });
    }

    private void setData() {
        if (mRespMarket != null && mTickHqRespReady) {
            if (mTickHqResp != null) {
                for (YsHqInfo ysHqInfo : mTickHqResp.getTickhqinfoList()) {
                    for (MarketInfoFragment mFragment : mFragments) {
                        mFragment.updateAdapter(exchangeData(ysHqInfo));
                    }
                }
            }
        }
    }

    private HqMsg.YsHqInfo exchangeData(YsHqInfo ysHqInfo) {
        HqMsg.YsHqInfo.Builder builder = HqMsg.YsHqInfo.newBuilder();
        builder.setCommodityNo(ysHqInfo.getCommodityNo());
        builder.setContractNo1(ysHqInfo.getContractNo1());
        builder.setQOpeningPrice(ysHqInfo.getQOpeningPrice());
        builder.setQLastPrice(ysHqInfo.getQLastPrice());
        builder.setQChangeRate(ysHqInfo.getQChangeRate());
        builder.setQChangeValue(ysHqInfo.getQChangeValue());
        return builder.build();
    }

    private void initFragments() {
        mTitleList.clear();
        mTitleId.clear();
        mFragments.clear();

        mTitleList.add("所有合约");
        mTitleList.add("自选");

        mTitleId.add("-2");
        mTitleId.add("-1");

        mFragments.add(new MarketInfoFragment().getInstance("-2"));
        mFragments.add(new MarketInfoFragment().getInstance("-1"));
        for (int i = 0; i < mRespMarket.getMarketList().size(); i++) {
            mTitleList.add(mRespMarket.getMarketList().get(i).marketName);
            mTitleId.add(mRespMarket.getMarketList().get(i).id);
            mFragments.add(new MarketInfoFragment().getInstance(mRespMarket.getMarketList().get(i).id));
        }
    }

    private void initNavigator() {
        CommonNavigator commonNavigator = new CommonNavigator(getContext());
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mTitleList == null ? 0 : mTitleList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                ColorTransitionPagerTitleView colorTransitionPagerTitleView = new ColorTransitionPagerTitleView(context);
                colorTransitionPagerTitleView.setNormalColor(getResources().getColor(R.color.color_T3));
                colorTransitionPagerTitleView.setSelectedColor(getResources().getColor(R.color.color_text_style4));
                colorTransitionPagerTitleView.setText(mTitleList.get(index));
                colorTransitionPagerTitleView.setTextSize(14);
                colorTransitionPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mViewPager.setCurrentItem(index);
                    }
                });
                return colorTransitionPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                indicator.setColors(getResources().getColor(R.color.color_text_style4));
                indicator.setLineWidth(DisplayUtil.dip2px(context, 24));
                indicator.setRoundRadius(DisplayUtil.dip2px(context, 1));
                indicator.setLineHeight(DisplayUtil.dip2px(context, 2));
                return indicator;
            }
        });
        mMagicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(mMagicIndicator, mViewPager);
        mViewPager.setOffscreenPageLimit(mFragments.size());
        mViewPager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return mFragments.get(position);
            }

            @Override
            public int getCount() {
                return mFragments.size();
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_search:
                OnEventUtils.onEvent(getActivity(), OnEventID.CONTRACT_SEARCH);
                startActivity(new Intent(getActivity(), SearchTreatyActivity.class));
                break;
            default:
                break;
        }
    }

    private void startCalculationService() {
        Intent intent = new Intent(getActivity(), CalculationService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            getActivity().startForegroundService(intent);
        } else {
            getActivity().startService(intent);
        }
    }

    /**
     * 初始化相机相关权限
     * 适配6.0+手机的运行时权限
     */
    private void initPermission() {
        String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.SYSTEM_ALERT_WINDOW};
        //检查权限
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 之前拒绝了权限，但没有点击 不再询问 这个时候让它继续请求权限
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                ActivityCompat.requestPermissions(getActivity(), permissions, SystemConfig.REQUEST_PERMISSIONS);
            } else {
                ActivityCompat.requestPermissions(getActivity(), permissions, SystemConfig.REQUEST_PERMISSIONS);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        switch (SystemConfig.REQUEST_PERMISSIONS) {
            case 1234:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    showToast("用户授权权限");
                } else if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_DENIED) {
                    showToast("用户拒绝权限");
                    Intent intent = CommonUtils.getAppDetailSettingIntent(getActivity());
                    startActivity(intent);
                }
                break;
            default:
                break;
        }
    }

}
